import {ref, getCurrentInstance, onMounted, nextTick, watch, toRaw} from "vue";
import {useStore} from "@/stores";

export function useListTabs(name: string, type: string | undefined=undefined) {
    const active = ref(name);
    const proxy: any = getCurrentInstance()?.proxy;
    const clickTabs: string[] = [];
    const store = useStore();

    const tabClick = (ctx: any, evt: any) => {
        if (!clickTabs.find(item => item === ctx.paneName)) {
            const rt = proxy.$refs[ctx.paneName];
            clickTabs.push(ctx.paneName);
            rt?.refresh()
        }
    }

    const clearTabs = () => {
        clickTabs.length = 0;
    }

    const handleCurrent = () => {
        const rt = proxy.$refs[active.value];
        if (!clickTabs.find(item => item === active.value)) {
            clickTabs.push(active.value);
        }
        nextTick(() => rt?.refresh()).then();
    }

    const handleSwitch = (target: string) => {
        active.value = name;
        clickTabs.splice(0, clickTabs.length);
    }

    onMounted(() => clickTabs.push(name));

    type && watch(
        () => store.currents[type],
        async (newVal: any, oldVal: any) => {
            clearTabs();
        }, {immediate: true}
    );

    return {
        active,
        tabClick,
        clearTabs,
        handleSwitch,
        handleCurrent,
    }
}
